<!--
 * @Descripttion: 产出数数据
 * @LastEditors: xzh
 * @LastEditTime: 2023-11-25 22:06:23
-->
<template>
  <div :class="['produceItem-container', `${dataType}-item`]">
    <el-card class="el-card-bottom-top">
      <template #header>
        <span>{{
          $t(
            `page.dashboardManageArr.produceDashboard.outputDataTypeArr.${dataType}`
          )
        }}</span>
        <el-date-picker
          v-model="dateValue"
          unlink-panels
          type="daterange"
          :start-placeholder="$t('common.statrDate')"
          :end-placeholder="$t('common.endDate')"
          :shortcuts="Dile_Methods.getShortcuts()"
          size="small"
          @change="initItemList"
        />
      </template>
      <!-- 图表 -->
      <div
        v-if="!produceFilterMap.chart.includes(dataType)"
        class="produceItem-chart"
      >
        <DileChart ref="chartRef" :loading="loading" :chart="chartData" />
      </div>
      <!-- 列表 -->
      <div
        v-if="!produceFilterMap.list.includes(dataType)"
        class="produceItem-list"
      >
        <DileTable v-loading="loading" ref="dileTableRef">
          <template #preColumn>
            <template
              v-for="(column, index) in ProduceDashboardUtils.tableColumnMap[
                dataType
              ]"
              :key="column.field"
            >
              <vxe-column
                :field="column.field"
                min-width="60"
                :width="column.width || ''"
                :title="
                  $t(column.title) + (!!column.unit ? `(${column.unit})` : ``)
                "
              >
                <template #default="{ row }">
                  <el-button
                    v-if="column.field == 'equipmentName'"
                    type="success"
                    link
                    @click="
                      emit('rowClick', { equipInfo: row, dataType, dateValue })
                    "
                    >{{ row[column.field] }}</el-button
                  >
                  <span v-else>
                    {{ `${row[column.field]}${column.unit || ""}` }}
                  </span>
                </template>
              </vxe-column>
            </template>
          </template>
        </DileTable>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, provide, onMounted, watchEffect } from "vue";
import { propsParam_Inf } from "@/components/dile-table/index.type";
import { object_Inf } from "@/utils/typings/index.type";
import {
  produceDataTypeEnum,
  produceDataTypeMap,
  produceFilterMap,
} from "../index.type";
import { dayjs } from "element-plus";
import ProduceDashboardUtils from "../utils";
import DileTable from "@/components/dile-table/index.vue";
import DileChart from "@/components/dile-chart/index.vue";
import DileTooltip from "@/components/dile-tooltip/index.vue";
import Dile_Methods from "@/utils/methods";
import Dile_APi from "@/api";
import Dile_StoreAction from "@/utils/cache/store";
const emit = defineEmits(["update:dataMap", "rowClick"]);
const props = defineProps({
  dataMap: {
    type: Object,
    requited: true,
    default: {},
  },
  dataType: {
    type: String,
    requited: true,
    default: "",
  },
  dateType: {
    type: String,
    requited: true,
    default: "",
  },
  loading: {
    type: Boolean,
    requited: true,
    default: true,
  },
});
/**
 * @Author: xzh
 * @Descripttion: 表格实例
 * @Param:
 */
let dileTableRef = ref<any>(null);
/**
 * @Author: xzh
 * @Descripttion: 图表数据
 * @Param:
 */
let chartData = ref<object_Inf>({});
/**
 * @Author: xzh
 * @Descripttion: 图表实例
 * @Param:
 */
let chartRef = ref<any>(null);

/**
 * @Author: xzh
 * @Descripttion: 日期筛选
 * @Param:
 */
let dateValue = ref<any>([
  Dile_Methods.getDefaultToDay(),
  Dile_Methods.getDefaultToDay(),
]);
/**
 * @Author: xzh
 * @Descripttion: 卸载监听
 * @Param:
 */
let stopWacth: any = null;

/**
 * @Author: xzh
 * @Descripttion: 初始化
 * @Param:
 */
onMounted(() => {
  stopWacth = watchEffect((onClear: Function) => {
    let { dataMap } = props;
    if (Object.keys(dataMap || {}).length > 0) {
      //清除副作用
      let timeOut = setTimeout(() => {
        initProduceItem();
        //停止监听
        stopWacth();
      }, 100);
      onClear(() => {
        clearTimeout(timeOut);
      });
    }
  });
});

/**
 * @Author: xzh
 * @Descripttion: 加载生成数据
 * @Param:
 */
let initProduceItem = async (coverDataMap: object_Inf = {}) => {
  let { dataType, dateType, dataMap } = props,
    { items = [] } =
      Object.keys(coverDataMap).length > 0 ? coverDataMap : dataMap;
  //修改表格数据
  Object.assign(propsParam, {
    tableData: items,
    emitEvents: {
      refreshTable: initItemList,
    },
  });
  //获取图表数据
  chartData.value = ProduceDashboardUtils.getProduceChart(
    dataType as produceDataTypeEnum,
    dateType,
    items
  );
  //加载图表
  chartRef.value?.init();
};
/**
 * @Author: xzh
 * @Descripttion: 时间筛选改变时间
 * @Param:
 */
let initItemList = async () => {
  try {
    propsParam.loading = true;
    let { dataType } = props,
      [startDate, endDate] = dateValue.value.map((x: any) =>
        dayjs(x).format("YYYY-MM-DD")
      ),
      //获取当前工厂
      { id } = Dile_StoreAction.getCurrentFactory(),
      api: string = "";
    switch (dataType) {
      case produceDataTypeEnum.aoi:
        //获取生产AOI良率
        api = "getProduceAOIYieldRate";
        break;
      case produceDataTypeEnum.aoiDefectRate:
        //获取生产AOI不良率
        api = "getProduceAOINotYieldRate";
        break;
      case produceDataTypeEnum.aoiTestNum:
        //AOI/CCD检验数
        api = "GetProduceAOIInspection";
        break;
      case produceDataTypeEnum.formingOutput:
      case produceDataTypeEnum.cutEdgeOutput:
      case produceDataTypeEnum.stackingOutput:
        //获取生产产出量
        api = "getProduceOutputDto";
        break;
      // case produceDataTypeEnum.formingEnergy:
      //   //获取生产能耗
      //   api = "getProducetEnergy";
      //   break;
      case produceDataTypeEnum.formingUtilization:
      case produceDataTypeEnum.cutEdgeUtilization:
      case produceDataTypeEnum.aoiUtilization:
        //获取稼动率
        api = "getProducetRate";
        break;
      case produceDataTypeEnum.formingUseRate:
        //获取使用率
        api = "getUsageRateDto";
        break;
    }
    let data = await Dile_APi[api]({
      startDate,
      endDate,
      orgId: id,
      type: produceDataTypeMap[dataType],
    });
    emit("update:dataMap", data);
    //加载生成数据
    await initProduceItem(data);
  } finally {
    propsParam.loading = false;
  }
};

/**
 * @Author: xzh
 * @Descripttion: 表格参数
 * @Param:
 */
let propsParam = reactive<propsParam_Inf>({
  tableData: [],
  loading: false,
  isPagination: false,
  // bottomUp: true,
  // maxHeight: 300,
  scrollX: {
    enabled: false,
  },
});
provide("propsParam", propsParam);

defineExpose({
  getDateValue: () => dateValue.value,
});
</script>
<style lang="scss" scoped>
.produceItem-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: var(--produceItem-gap);
  .produceItem-count {
    display: flex;
    background-color: #00bfbf;
    border-radius: var(--produceItem-gap);
    color: var(--el-color-white);
    padding: var(--produceItem-gap);
    gap: 1.75rem;
    > div {
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      > span:last-child {
        font-size: 1.75rem;
      }
    }
  }
  .el-card {
    .produceItem-chart,
    .produceItem-list {
      height: 13rem;
    }
    :deep(.el-card__header) {
      justify-content: space-between;
      align-items: center;
      height: max-content !important;
      > .el-date-editor {
        flex: 12.2rem 0 0;
      }
    }
  }

  --produceItem-gap: 0.5rem;
}
</style>
